#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sqlite3
import pandas as pd
from tabulate import tabulate
import argparse

def view_db_content():
    """直接读取并显示数据库内容"""
    # 数据库文件路径
    db_path = os.path.join(os.path.dirname(__file__), "../data/prompts.db")
    
    if not os.path.exists(db_path):
        print(f"错误：数据库文件不存在：{db_path}")
        return
    
    try:
        # 连接数据库
        conn = sqlite3.connect(db_path)
        
        # 获取所有表名
        cursor = conn.cursor()
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
        tables = cursor.fetchall()
        
        if not tables:
            print("数据库中没有表格")
            return
        
        print(f"数据库 {db_path} 中共有 {len(tables)} 个表格:")
        
        # 显示每个表的内容
        for table in tables:
            table_name = table[0]
            print(f"\n{'='*80}")
            print(f"表格：{table_name}")
            print(f"{'='*80}")
            
            # 获取行数
            cursor.execute(f"SELECT COUNT(*) FROM {table_name}")
            row_count = cursor.fetchone()[0]
            print(f"共有 {row_count} 条记录")
            
            # 获取列信息
            cursor.execute(f"PRAGMA table_info({table_name})")
            columns_info = cursor.fetchall()
            columns = [col[1] for col in columns_info]
            print(f"列名：{', '.join(columns)}")
            
            # 读取数据
            df = pd.read_sql_query(f"SELECT * FROM {table_name} LIMIT 15", conn)
            
            # 处理长文本，避免显示过长
            for col in df.columns:
                if df[col].dtype == 'object':
                    df[col] = df[col].apply(lambda x: str(x)[:80] + '...' if isinstance(x, str) and len(str(x)) > 80 else x)
            
            # 显示数据表格
            print("\n前15条记录:")
            print(tabulate(df, headers='keys', tablefmt='pretty', showindex=True))
            
            # 显示数据统计信息
            numeric_cols = df.select_dtypes(include=['number']).columns
            if not numeric_cols.empty:
                print("\n数值列统计信息:")
                stats_df = df[numeric_cols].describe().T
                print(tabulate(stats_df, headers='keys', tablefmt='pretty'))
    
    except Exception as e:
        print(f"读取数据库时出错: {str(e)}")
    
    finally:
        if 'conn' in locals():
            conn.close()

def main():
    parser = argparse.ArgumentParser(description="查看数据库内容")
    parser.add_argument("--detail", action="store_true", help="显示更详细的信息")
    args = parser.parse_args()
    
    view_db_content()

if __name__ == "__main__":
    main()